<?php

namespace app\api\controller;

use app\api\model\Remark;
use app\api\model\TexRemark;
use think\cache\driver\Redis;
use think\Controller;
use think\Db;
use think\Request;

class Text extends Controller
{
    /**
     * @return \think\response\Json
     * @throws \think\exception\DbException
     * 文章列表
     */
    public function textList()
    {
        $redis = new Redis();
        if ($redis->get('textList')) {
            //查找全部
            return getJson(200, '加载成功', $redis->get('textList'));
        } else {
            $data = \app\api\model\Text::all();
            $redis->set('textList', $data);
            return getJson(200, '加载成功', $data);
        }

    }

    /**
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 文章详情
     */
    public function textDetail()
    {
        $id = input('id');
        //查找单条
        $data = \app\api\model\Text::where('text_id', $id)->find();
        return getJson(200, '加载成功', $data);
    }

    /**
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 文章浏览量加1
     */
    public function textBrowseNum()
    {
        $id = input('id');
        //查找加浏览量的文章
        $data = \app\api\model\Text::where('text_id', $id)->find();
        $info = [
            'text_id' => $id,
            'browse_num' => $data['browse_num'] + 1
        ];
        $res = \app\api\model\Text::update($info, $id);
        if ($res) {
            return getJson(200, '浏览成功', $info);
        } else {
            return getJson(500, '加载失败');
        }
    }

    /**
     * @return \think\response\Json
     * 添加评论
     */
    public function remarkInsert()
    {
        $data = input();
        $info = [
            'tid' => $data['id'],
            'remark_detail' => $data['remark']
        ];
        $detection = doAudit($data['remark']);

        $res = Remark::create($info, true);
        if (!$res) {
            return getJson('500', '评论失败');
        }
        //获取上一次添加的id
        $insertId = Db::table('remark')->getLastInsID();
        $info['rid'] = $insertId;
        $resText = TexRemark::create($info, true);
        if ($resText) {
            return getJson('200', '评论成功', $info);
        } else {
            return getJson('500', '评论失败');
        }
    }

    /**
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 评论列表
     */
    public function remarkList()
    {
        $textId = input('id');
        //获取评论
        $res = Remark::join('text_remark', 'text_remark.rid=remark.remark_id')->where('tid', $textId)->select();
        return getJson('200', '评论成功', $res);
    }
}
